#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-09-07 22:57
# @Author : hard work
# @File    : stc_py_demo1.py
# @Description :
# python 版本注意
import os, sys
import time

stcInstallDir = 'C:\Program Files\Spirent Communications\Spirent TestCenter 5.13\Spirent TestCenter Application'

stcPythonlibDir = stcInstallDir + '/API/Python'
os.environ['STC_PRIVATE_INSTALL_DIR'] = stcInstallDir
sys.path.append(stcPythonlibDir)
from StcPython import StcPython

print("正在实例化对象")
stc = StcPython()
print("实例化完成")
ip = '10.132.238.189'
slotport1 = '1/3'
slotport2 = '1/4'
print("正在绑定端口" + slotport1 + "和端口" + slotport2)
stc.create("project")
port1 = stc.create('port', under="project1")
port2 = stc.create('port', under="project1")
stc.config(port1, location="//%s/%s" % (ip, slotport1))
stc.config(port2, location="//%s/%s" % (ip, slotport2))
portlist = stc.get("project1", "children-port")
stc.perform("attachports", portList=str(portlist), autoConnect='TRUE')
stc.apply()
print("绑定端口完毕")

gen = stc.subscribe(Parent="project1", ResultParent=port1, ConfigType='Generator', resulttype='GeneratorPortResults')
ana = stc.subscribe(Parent="project1", ResultParent=port2, ConfigType='Analyzer', resulttype='AnalyzerPortResults')
hGenerator = stc.get(port1, "children-Generator")
hAnalyzer = stc.get(port2, "children-Analyzer")

tx = stc.subscribe(Parent="project1", ResultParent=port1, ConfigType='streamblock', resulttype='txstreamresults')
rx = stc.subscribe(Parent="project1", ResultParent=port2, ConfigType='streamblock', resulttype='rxstreamsummaryresults')

hDevice1 = stc.create("emulateddevice", under="project1")
# 必须设置网关为对方的地址 否则会一直寻找网关 然后一直arp解析失败
hIpv4If1 = stc.create("Ipv4If", under=hDevice1, Address="192.85.1.3", Gateway="192.85.1.4")
hEthIIIf1 = stc.create("EthIIIf", under=hDevice1, SourceMac="00:10:94:00:00:03")
stc.config(port1, **{"AffiliationPort-sources": hDevice1})
stc.config(hDevice1, **{"TopLevelIf-targets": [hIpv4If1]})
stc.config(hDevice1, **{"PrimaryIf-targets": [hIpv4If1]})
stc.config(hIpv4If1, **{"StackedOnEndpoint-targets": [hEthIIIf1]})

hDevice2 = stc.create("emulateddevice", under="project1")
# 和上面那个网关同理
hIpv4If2 = stc.create("Ipv4If", under=hDevice2, Address="192.85.1.4", Gateway="192.85.1.3")
hEthIIIf2 = stc.create("EthIIIf", under=hDevice2, SourceMac="00:10:94:00:00:04")
stc.config(port2, **{"AffiliationPort-sources": hDevice2})
stc.config(hDevice2, **{"TopLevelIf-targets": [hIpv4If2]})
stc.config(hDevice2, **{"PrimaryIf-targets": [hIpv4If2]})
stc.config(hIpv4If2, **{"StackedOnEndpoint-targets": [hEthIIIf2]})

src = stc.get(hDevice1, "children-ipv4if")
dst = stc.get(hDevice2, "children-ipv4if")
# 帧长
a = [128, 256, 512, 1024]
# 这个变量用于记录前一个的帧长度
pretx = 0
prerx = 0
for i in a:  # 字长
    for j in range(10, 110, 10):  # 负载
        hGeneratorConfig = stc.get(hGenerator, "children-GeneratorConfig")
        stc.config(hGeneratorConfig,
                   LoadMode="FIXED",
                   FixedLoad=j,
                   LoadUnit="PERCENT_LINE_RATE")
        hStreamBlock = stc.create("streamBlock", under=port1, insertSig="true", frameConfig="EthernetII IPv4 Udp", \
                                  frameLengthMode="FIXED", FixedFrameLength=i)
        stc.config(hStreamBlock, **{"SrcBinding-targets": [src]})
        stc.config(hStreamBlock, **{"DstBinding-targets": [dst]})
        stc.perform("streamblockUpdate", streamblock=hStreamBlock)
        stc.apply()

        stc.perform("CaptureStart", CaptureProxyId=port2)
        stc.perform("CaptureStart", CaptureProxyId=port1)
        stc.perform("ArpNdStartOnAllStreamBlocksCommand")
        stc.perform("ArpNdStartOnAllDevicesCommand")
        stc.perform('GeneratorStart')
        time.sleep(5)
        stc.perform('GeneratorStop')
        stc.perform("CaptureStop", CaptureProxyId=port2)
        stc.perform("CaptureStop", CaptureProxyId=port1)
        stc.perform("CaptureDataSave", CaptureProxyId=port2, FileName="2.pcap", FileNamePath="D:/")
        stc.perform("CaptureDataSave", CaptureProxyId=port1, FileName="1.pcap", FileNamePath="D:/")
        # print("save D:/1.pcap" )
        # 判断是否丢包
        tx = stc.get(stc.get(gen, 'ResultHandleList'), 'GeneratorSigFrameCount')
        rx = stc.get(stc.get(ana, 'ResultHandleList'), 'SigFrameCount')
        ttx = int(tx) - pretx
        trx = int(rx) - prerx
        print("字长：" + str(i) + " 负载:" + str(j) + "% 发送帧数：" + str(ttx))
        print("字长：" + str(i) + " 负载:" + str(j) + "% 接收帧数：" + str(trx))
        pretx = int(tx)
        prerx = int(rx)
        # data是前面运行出的数据，先将其转为字符串才能写入
        with open('结果存放2.txt', 'a') as file_handle:  # .txt可以不自己新建,代码会自动新建
            file_handle.write(str(ttx))  # 写入
            file_handle.write('\n')  # 有时放在循环里面需要自动转行，不然会覆盖上一条数据

stc.perform("SaveAsXml", filename='D:/1.xml')
